package squidadm.www.rest;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeSet;
import javax.servlet.ServletContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

/**
 * @author moroz
 */
@Path("/allowed/sites")
public class AllowedSitesRS {

    protected String squidConfDirectory = "",
            squidConfAllowedSitesName = "";

    @Context
    public void setServletContext(ServletContext context) {
        squidConfDirectory = context.getInitParameter("squid-conf-directory");
        squidConfAllowedSitesName = context.getInitParameter("squid-conf-allowed-sites-name");
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getAllowedSitesList() {
        LineNumberReader reader = null;
        try {
            reader = new LineNumberReader(new FileReader(squidConfDirectory
                    + "/"
                    + squidConfAllowedSitesName));

            TreeSet<String> sites = new TreeSet<String>();
            for (String line = ""; line != null; line = reader.readLine()) {
                if (line.length() > 0) {//igonre empty lines
                    sites.add(line);
                }
            }

            return Response.ok()
                    .entity(sites)
                    .header("X-Sites-Count", sites.size())
                    .build();
        } catch (IOException e) {
            return Response.serverError().build();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {

                }
            }
        }

    }
}
